export interface UserAgent {
  browser: {
    name: string;
    version: string;
  };
  os: {
    name: string;
    version: string;
  };
  platform: string;
}

export function parse(userAgentString: string): UserAgent {
  const ua = userAgentString.toLowerCase();

  // 检测浏览器
  let browserName = 'Unknown';
  let browserVersion = '';

  if (ua.includes('micromessenger')) {
    browserName = 'WeChat';
    const match = ua.match(/micromessenger\/(\d+\.?\d*)/);
    browserVersion = match ? match[1] : '';
  } else if (ua.includes('chrome')) {
    browserName = 'Chrome';
    const match = ua.match(/chrome\/(\d+\.?\d*)/);
    browserVersion = match ? match[1] : '';
  } else if (ua.includes('firefox')) {
    browserName = 'Firefox';
    const match = ua.match(/firefox\/(\d+\.?\d*)/);
    browserVersion = match ? match[1] : '';
  } else if (ua.includes('safari')) {
    browserName = 'Safari';
    const match = ua.match(/safari\/(\d+\.?\d*)/);
    browserVersion = match ? match[1] : '';
  } else if (ua.includes('edge')) {
    browserName = 'Edge';
    const match = ua.match(/edge\/(\d+\.?\d*)/);
    browserVersion = match ? match[1] : '';
  }

  // 检测操作系统
  let osName = 'Unknown';
  let osVersion = '';

  if (ua.includes('windows')) {
    osName = 'Windows';
    if (ua.includes('windows nt 10.0')) osVersion = '10';
    else if (ua.includes('windows nt 6.3')) osVersion = '8.1';
    else if (ua.includes('windows nt 6.2')) osVersion = '8';
    else if (ua.includes('windows nt 6.1')) osVersion = '7';
  } else if (ua.includes('mac os x')) {
    osName = 'macOS';
    const match = ua.match(/mac os x (\d+[._]\d+)/);
    osVersion = match ? match[1].replace('_', '.') : '';
  } else if (ua.includes('android')) {
    osName = 'Android';
    const match = ua.match(/android (\d+\.?\d*)/);
    osVersion = match ? match[1] : '';
  } else if (ua.includes('iphone') || ua.includes('ipad')) {
    osName = 'iOS';
    const match = ua.match(/os (\d+[._]\d+)/);
    osVersion = match ? match[1].replace('_', '.') : '';
  } else if (ua.includes('linux')) {
    osName = 'Linux';
  }

  // 检测平台
  let platform = 'desktop';
  if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone')) {
    platform = 'mobile';
  } else if (ua.includes('ipad') || ua.includes('tablet')) {
    platform = 'tablet';
  }

  return {
    browser: {
      name: browserName,
      version: browserVersion
    },
    os: {
      name: osName,
      version: osVersion
    },
    platform
  };
}